using AutoMapper;
using MediatR;
using RBAC.Domain.MaterialManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.MaterialFile;

namespace RBAC.Write.Api.Application.Handler.ERP.MaterialFile
{
    /// <summary>
    /// 删除物料处理程序
    /// </summary>
    public class DeleteMaterialHandler : IRequestHandler<DeleteMaterialCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<Mater> materRepository;
        private readonly ILogger<DeleteMaterialHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="materRepository">物料仓储接口</param>
        /// <param name="logger">日志接口</param>
        public DeleteMaterialHandler(
            IBaseRepository<Mater> materRepository,
            ILogger<DeleteMaterialHandler> logger)
        {
            this.materRepository = materRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 处理删除物料请求
        /// </summary>
        /// <param name="request">删除物料请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        public async Task<APIResult<bool>> Handle(DeleteMaterialCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<bool>();

            try
            {
                logger.LogInformation("开始删除物料: {Id}", request.Id);

                // 1. 验证物料是否存在且未被删除
                var existingMater = materRepository.QueryFirstOrDefault<Mater>(
                    "SELECT * FROM Mater WHERE Id = @Id AND IsDeleted = false",
                    new { request.Id });

                if (existingMater == null)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "物料不存在或已被删除";
                    logger.LogWarning("物料不存在或已被删除: {Id}", request.Id);
                    return result;
                }

                // 2. 检查物料是否被引用（可选，根据业务需求）
                // 这里可以添加业务规则检查，例如检查是否有库存、是否有未完成的订单等

                // 3. 执行逻辑删除（更新IsDeleted字段为true）
                var affectedRows = materRepository.Execute(
                    "UPDATE Mater SET IsDeleted = true WHERE Id = @Id AND IsDeleted = false",
                    new { request.Id });

                if (affectedRows > 0)
                {
                    result.Code = APIEnums.Success;
                    result.Msg = "删除成功";
                    result.Data = true;
                    logger.LogInformation("物料删除成功: {Id}", request.Id);
                }
                else
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "删除失败，未找到匹配的记录";
                    logger.LogWarning("物料删除失败，未找到匹配记录: {Id}", request.Id);
                }
            }
            catch (Exception ex)
            {
                result.Code = APIEnums.Error;
                result.Msg = "删除失败，请稍后重试";
                logger.LogError(ex, "删除物料异常: {Id}", request.Id);
            }

            return result;
        }
    }
}